import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../models/device_model.dart';
import '../../../utils/themes/app_theme_extension.dart';
import '../../../translations/app_translations.dart';
import '../controllers/device_controller.dart';

class DeviceListItem extends StatelessWidget {
  final Device device;
  final VoidCallback? onTap;
  final VoidCallback onActionTap;
  final VoidCallback onDetailsTap;
  final VoidCallback onDataTap;
  final VoidCallback? onDataTableTap;

  const DeviceListItem({
    Key? key,
    required this.device,
    this.onTap,
    required this.onActionTap,
    required this.onDetailsTap,
    required this.onDataTap,
    this.onDataTableTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final extension = theme.extension<AppThemeExtension>();
    
    print('列表项 - 设备 ${device.deviceId} - ${device.deviceName} 的图片URL: ${device.deviceImage}');
    print('列表项 - 设备 ${device.deviceId} - 国标设备ID: "${device.wvpDeviceId}" 序列号: ${device.deviceSn}');
    
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      elevation: 2,
      clipBehavior: Clip.antiAlias,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(extension?.cardRadius ?? 8),
        side: BorderSide(color: extension?.cardBorder ?? Colors.grey.shade200),
      ),
      child: InkWell(
        onTap: onDetailsTap,
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Stack(
            children: [
              _buildDeviceImageArea(theme),
                  // 添加摄像头图标（如果设备有国标监控ID）
                  if (device.wvpDeviceId.isNotEmpty)
                    Positioned(
                      top: 0,
                      right: 0,
                      child: Container(
                        padding: const EdgeInsets.all(4),
                        decoration: BoxDecoration(
                          color: Colors.red.withOpacity(0.8),
                          borderRadius: const BorderRadius.only(
                            topRight: Radius.circular(8),
                            bottomLeft: Radius.circular(8),
                          ),
                        ),
                        child: InkWell(
                          onTap: () {
                            Get.find<DeviceController>().viewDeviceVideo(device.deviceId);
                          },
                          child: const Icon(
                            Icons.videocam,
                            color: Colors.white,
                            size: 16,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      device.deviceName ?? LocaleKeys.unnamedDevice.tr,
                      style: theme.textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '${LocaleKeys.serialNumber.tr}: ${device.deviceSn}',
                      style: theme.textTheme.bodyMedium?.copyWith(
                        color: extension?.textSecondary,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 2),
                    Text(
                      '${LocaleKeys.product.tr}: ${device.productName ?? LocaleKeys.unknownProduct.tr}',
                      style: theme.textTheme.bodyMedium?.copyWith(
                        color: extension?.textSecondary,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    
                    const SizedBox(height: 4),
                    _buildStatusChip(device.status),
                  ],
                ),
              ),
              const SizedBox(width: 16),
              Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 添加摄像头按钮（如果有国标ID）
                  if (device.wvpDeviceId.isNotEmpty) ...[
                    SizedBox(
                      width: 40,
                      height: 40,
                      child: OutlinedButton(
                        onPressed: () {
                          Get.find<DeviceController>().viewDeviceVideo(device.deviceId);
                        },
                        style: OutlinedButton.styleFrom(
                          padding: EdgeInsets.zero,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                          side: BorderSide(color: Colors.red.withOpacity(0.7)),
                        ),
                        child: const Icon(Icons.videocam, size: 20, color: Colors.red),
                      ),
                    ),
                    const SizedBox(height: 8),
                  ],
                  SizedBox(
                    width: 40,
                    height: 40,
                    child: OutlinedButton(
                      onPressed: onDataTap,
                      style: OutlinedButton.styleFrom(
                        padding: EdgeInsets.zero,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        side: BorderSide(color: theme.primaryColor.withOpacity(0.5)),
                      ),
                      child: Icon(Icons.show_chart, size: 20, color: theme.primaryColor),
                    ),
                  ),
                  if (onDataTableTap != null) ...[
                    const SizedBox(height: 8),
                    SizedBox(
                      width: 40,
                      height: 40,
                      child: OutlinedButton(
                        onPressed: onDataTableTap,
                        style: OutlinedButton.styleFrom(
                          padding: EdgeInsets.zero,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                          side: BorderSide(color: theme.primaryColor.withOpacity(0.5)),
                        ),
                        child: Icon(Icons.table_chart, size: 20, color: theme.primaryColor),
                      ),
                    ),
                  ],
                  const SizedBox(height: 8),
                  IconButton(
                    icon: const Icon(Icons.more_vert, size: 20),
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                    onPressed: onActionTap,
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
  
  Widget _buildDeviceStatusIcon(int? status) {
    IconData iconData;
    Color iconColor;
    
    switch (status) {
      case 0: // 未激活
        iconData = Icons.device_unknown;
        iconColor = Colors.grey;
        break;
      case 1: // 在线
        iconData = Icons.check_circle_outline;
        iconColor = Colors.green;
        break;
      case 2: // 离线
        iconData = Icons.offline_bolt;
        iconColor = Colors.orange;
        break;
      case 3: // 禁用
        iconData = Icons.block;
        iconColor = Colors.red;
        break;
      default:
        iconData = Icons.device_unknown;
        iconColor = Colors.grey;
    }
    
    final Color bgColor = Color.fromRGBO(
      iconColor.red, 
      iconColor.green, 
      iconColor.blue, 
      0.16
    );
    
    return CircleAvatar(
      backgroundColor: bgColor,
      radius: 20,
      child: Icon(iconData, color: iconColor, size: 22),
    );
  }
  
  Widget _buildStatusChip(int? status) {
    final theme = Get.theme;
    final extension = theme.extension<AppThemeExtension>();
    
    String label;
    Color color;
    Color textColor = Colors.white;
    
    switch (status) {
      case 0: // 未激活
        label = LocaleKeys.deviceInactive.tr;
        color = extension?.disabledBg ?? Colors.grey.shade200;
        textColor = extension?.disabledText ?? Colors.grey;
        break;
      case 1: // 在线
        label = LocaleKeys.deviceOnline.tr;
        color = extension?.successBg ?? Colors.green.shade100;
        textColor = extension?.successText ?? Colors.green;
        break;
      case 2: // 离线
        label = LocaleKeys.deviceOffline.tr;
        color = extension?.warningBg ?? Colors.orange.shade100;
        textColor = extension?.warningText ?? Colors.orange;
        break;
      case 3: // 禁用
        label = LocaleKeys.deviceDisabled.tr;
        color = extension?.errorBg ?? Colors.red.shade100;
        textColor = extension?.errorText ?? Colors.red;
        break;
      default:
        label = LocaleKeys.statusUnknown.tr;
        color = extension?.disabledBg ?? Colors.grey.shade200;
        textColor = extension?.disabledText ?? Colors.grey;
    }
    
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Text(
        label, 
        style: TextStyle(
          color: textColor, 
          fontSize: 12,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  Widget _buildDeviceImageArea(ThemeData theme) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(8),
      child: Container(
        width: 60,
        height: 60,
        decoration: BoxDecoration(
          color: theme.brightness == Brightness.dark 
              ? Colors.grey.shade800 
              : Colors.grey.shade200,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Stack(
          children: [
            Positioned.fill(
              child: device.deviceImage.isNotEmpty
                  ? Image.network(
                      device.deviceImage,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        print('列表项 - 设备图片加载错误: $error');
                        return _buildDefaultDeviceIcon(theme);
                      },
                      loadingBuilder: (context, child, loadingProgress) {
                        if (loadingProgress == null) return child;
                        return Center(
                          child: CircularProgressIndicator(
                            value: loadingProgress.expectedTotalBytes != null
                                ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes!
                                : null,
                            strokeWidth: 2,
                          ),
                        );
                      },
                    )
                  : _buildDefaultDeviceIcon(theme),
            ),
            Positioned(
              right: 0,
              bottom: 0,
              child: _buildStatusIndicator(device.status),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDefaultDeviceIcon(ThemeData theme) {
    IconData iconData;
    Color iconColor;
    
    switch (device.status) {
      case 0: // 未激活
        iconData = Icons.device_unknown;
        iconColor = Colors.grey;
        break;
      case 1: // 在线
        iconData = Icons.check_circle_outline;
        iconColor = Colors.green;
        break;
      case 2: // 离线
        iconData = Icons.offline_bolt;
        iconColor = Colors.orange;
        break;
      case 3: // 禁用
        iconData = Icons.block;
        iconColor = Colors.red;
        break;
      default:
        iconData = Icons.devices;
        iconColor = theme.primaryColor;
    }
    
    return Center(
      child: Icon(
        iconData,
        color: iconColor,
        size: 28,
      ),
    );
  }

  Widget _buildStatusIndicator(int? status) {
    Color color;
    switch (status) {
      case 0: // 未激活
        color = Colors.grey;
        break;
      case 1: // 在线
        color = Colors.green;
        break;
      case 2: // 离线
        color = Colors.orange;
        break;
      case 3: // 禁用
        color = Colors.red;
        break;
      default:
        color = Colors.grey;
    }

    return Container(
      width: 12,
      height: 12,
      margin: const EdgeInsets.all(4),
      decoration: BoxDecoration(
        color: color,
        shape: BoxShape.circle,
        border: Border.all(color: Colors.white, width: 2),
      ),
    );
  }
} 